<template>
  <div class="overflow-auto relative flex flex-col items-center">
    <m-svg-icon
      v-if="isMobileTerminal"
      name="close"
      class="w-3 h-3 p-0.5 m-1 ml-auto"
      fillClass="fill-zinc-900 dark:fill-zinc-200 "
      @click="close"
    />

    <img id="image" class="" ref="imageTarget" :src="props.currentBlobURL" />

    <m-button
      :loading="loading"
      class="mt-4 w-[80%] xl:w-1/2"
      @click="onConfirmClick"
    >
      确定
    </m-button>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import { isMobileTerminal } from '@/utils/flexibal'
import { getOSSClient } from '@/utils/sts'
import { message } from '@/libs'
import { editUserInfo } from '@/api/sys'

const emits = defineEmits(['handleClose'])
import { useStore } from 'vuex'
const store = useStore()
const props = defineProps({
  currentBlobURL: {
    type: String,
    default: ''
  }
})

const imageTarget = ref(null)
const loading = ref(false)
const cropperImg = ref()
// 移动端配置对象
const mobileOptions = {
  // 将裁剪框限制在画布的大小
  viewMode: 1,
  // 移动画布，裁剪框不动
  dragMode: 'move',
  // 裁剪框固定纵横比：1:1
  aspectRatio: 1,
  // 裁剪框不可移动
  cropBoxMovable: false,
  // 不可调整裁剪框大小
  cropBoxResizable: false
}

// PC 端配置对象
const pcOptions = {
  // 裁剪框固定纵横比：1:1
  aspectRatio: 1
}
onMounted(() => {
  cropperImg.value = new Cropper(
    imageTarget.value,
    isMobileTerminal.value ? mobileOptions : pcOptions
  )
})
const close = () => {
  emits('handleClose')
}
const onConfirmClick = () => {
  loading.value = true

  cropperImg.value.getCroppedCanvas().toBlob((blob) => {
    putObjectToOss(blob)
  })
}
const ossClinter = ref()
// 进行图片上传
const putObjectToOss = async (file) => {
  if (!ossClinter.value) {
    ossClinter.value = await getOSSClient()
  }
  try {
    const fileType = file.type.split('/')
    const fineName = `${store.getters.userInfo.username}/${Date.now()}.${
      fileType[fileType.length - 1]
    }`
    const res = await ossClinter.value.put(`images/${fineName}`, file)
    updateUserInfo(res)
  } catch (error) {
    message('error', error)
  }
}

// 更新本地数据与服务器数据
const updateUserInfo = async (res) => {
  // 更新本地数据
  store.commit('user/setUserInfo', {
    ...store.getters.userInfo,
    avatar: res.url
  })
  // 更新服务器
  await editUserInfo(store.getters.userInfo)
  message('success', '修改成功')
  loading.value = false
  close()
}
</script>
<style scoped lang="scss">
/* 确保图像的大小完全适合容器 */
img {
  display: block;
  max-width: 100%;
}
</style>
